<?php
// ========================== 文件说明 ==========================//
// 本文件说明：文档分享
// --------------------------------------------------------------//
// 本程序作者：黄进
// --------------------------------------------------------------//
// 本程序版本：SaBlog-X Ver 2.0
// --------------------------------------------------------------//
// 本程序主页：http://huangj.in
// ========================== 开发环境 ==========================//
// register_globals = Off
// --------------------------------------------------------------//
// magic_quotes_gpc = On
// --------------------------------------------------------------//
// safe_mode = On
// --------------------------------------------------------------//
// Windows server 2003 & Linux & FreeBSD
// --------------------------------------------------------------//
// Apache/1.3.33 & PHP/4.3.2 & MySQL/4.0.17
// --------------------------------------------------------------//
// Apache/1.3.34 & PHP/4.4.1 & MySQL/5.0.16
// --------------------------------------------------------------//
// Apache/2.0.55 & PHP/5.1.1 & MySQL/5.0.15
// --------------------------------------------------------------//
// Copyright (C) Security Angel Team All Rights Reserved.
// ==============================================================//

if(!defined('SABLOG_ROOT') || !isset($php_self) || !preg_match("/[\/\\\\]cp\.php$/", $php_self)) {
	exit('Access Denied');
}

// 加载附件相关函数
require_once(SABLOG_ROOT.'include/func/attachment.func.php');

$uquery = '';
if ($sax_group != 1) {
	$uquery = " AND uid='$sax_uid'";
}

!$action && $action = 'add';

$catedb = array();
$query = $DB->query("SELECT cid,name FROM {$db_prefix}files_categories ORDER BY displayorder");
while ($cate = $DB->fetch_array($query)) {
	$catedb[$cate['cid']] = $cate['name'];
}
unset($cate);
$DB->free_result($query);

if($_POST['action'] == 'addfiles') {
	// 取值并过滤部分
	$cid          = intval($_POST['cid']);
	$filedescription  = htmlspecialchars(trim($_POST['filedescription']));

//关键词日后在增加上去
/*	$keywords    = str_replace('，', ',', $keywords);
	$keywords    = str_replace(',,', ',', $keywords);
	if (substr($keywords, -1) == ',') {
		$keywords = substr($keywords, 0, strlen($keywords)-1);
	}*/

	// 暂时把提交的数据保存到COOKIE
	// 2880分钟=2天
	scookie('cid',$cid,2880);
	scookie('filedescription',$filedescription,2880);

	// 检查变量
	checktitle($filename);
	checkcate($cid);
//	日后增加关键词
//	checkkeywords($keywords);
	$posttime = $timestamp;

	$filename = char_cv($filename);
	$r = $DB->fetch_one_array("SELECT attachmentid FROM {$db_prefix}files_attachments WHERE filename='$filename' and cid='$cid' and filedescription='$filedescription' LIMIT 1");
	if ($r) {
		redirect('数据库中已存在相同的数据', 'cp.php?job=files&action=add');
	}
	// 上传附件
	$searcharray = array();
	$replacearray = array();
$attachments = $attachs = array();

if(isset($_FILES['attach']) && is_array($_FILES['attach'])) {
	foreach($_FILES['attach'] as $key => $var) {
		foreach($var as $id => $val) {
			$attachments[$id][$key] = $val;
		}
	}
}

if($attachments) {
	$gd_version = gd_version();
	foreach($attachments as $key => $attach) {
		if(!disuploadedfile($attach['tmp_name']) || !($attach['tmp_name'] != 'none' && $attach['tmp_name'] && $attach['name'])) {
			continue;
		}

		$attach['name'] = strtolower($attach['name']);
		$attach['ext']  = getextension($attach['name']);

		$fnamehash = md5(uniqid(microtime()));
		$attachsubdir = '/'.$options['files_attachments_dir'].'/date_'.sadate('Ym').'/';
		// 取得附件目录的绝对路径
		$attach_dir = SABLOG_ROOT.$options['attachments_dir'].$attachsubdir;
		if(!is_dir($attach_dir)) {
			mkdir($attach_dir, 0777);
			@chmod($attach_dir, 0777);
			fclose(fopen($attach_dir.'index.htm', 'w'));
		}
		// 判断上传的类型
		// path变量为管理目录相对路径,后台操作用
		// filepath变量为跟目录相对路径,前台读取用
		// fnamehash变量为当前时间的MD5散列,重命名附件名
		if (!in_array($attach['ext'], array('gif', 'jpg', 'jpeg', 'png'))) {
			$path     = $attach_dir.$fnamehash.'.file';
			$filepath = $attachsubdir.$fnamehash.'.file';
		} else {
			$path     = $attach_dir.$fnamehash.'.'.$attach['ext'];
			$filepath = $attachsubdir.$fnamehash.'.'.$attach['ext'];
		}
		$attachment = upfile($attach['tmp_name'], $path);
		// 如果一种函数上传失败，还可以用其他函数上传
		if (!$attachment) {
			redirect('上传附件发生意外错误!');
		}

		$tmp_filesize = @filesize($attachment);
		if ($tmp_filesize != $attach['size']) {
			@unlink($attachment);
			redirect('上传附件发生意外错误!');
		}
		// 判断是否为图片格式
		if (in_array($attach['ext'], array('gif', 'jpg', 'jpeg', 'png'))) {
			if ($imginfo=@getimagesize($attachment)) {
				if (!$imginfo[2] || !$imginfo['bits']) {
					@unlink($attachment);
					redirect('上传的文件不是一个有效的GIF或者JPG文件!');
				} else {
					$isimage = '1';
				}
			}
		}
		// 把文件信息插入数据库
		$DB->query("INSERT INTO {$db_prefix}files_attachments (cid, uid, dateline, filename, filetype, filesize, downloads, filepath, fileext, filedescription) VALUES ('$cid', '$sax_uid', '$posttime', '".sax_addslashes($attach['name'])."', '".sax_addslashes($attach['type'])."', '".$attach['size']."', '0', '".sax_addslashes($filepath)."', '".$attach['ext']."', '$filedescription')");
		$aidtmp = $DB->insert_id();
		// 更新文档分类数量
		$DB->unbuffered_query("UPDATE {$db_prefix}files_categories SET articles=articles+1 WHERE cid='$cid'");
		$attachs[$aidtmp] = array(
			'attachmentid' => $aidtmp,
			'dateline' => $timestamp,
			'filename' => sax_addslashes($attach['name']),
			'filetype' => sax_addslashes($attach['type']),
			'filepath' => sax_addslashes($filepath),
			'filesize' => sax_addslashes($attach['size']),
			'downloads' => 0,
			'isimage' => $isimage
		);
		unset($isimage);

	}
}

$attachment_count = count($attachs);
$attachmentids = 0;
foreach($attachs as $key => $value){
	$attachmentids .= ','.$key;
}
$attachs = $attachs ? sax_addslashes(serialize($attachs)) : '';
	// 上传结束

	// 插入数据部分
/*	$attachmentid = $DB->insert_id();
	$DB->unbuffered_query("UPDATE {$db_prefix}users SET articles=articles+1 WHERE userid='$sax_uid'");
	if($attachmentids){
		$DB->unbuffered_query("UPDATE {$db_prefix}files_attachments SET attachmentid='$attachmentid' WHERE attachmentid IN($attachmentids)");
	}*/

/*	// 插入/更新Tags
	if ($keywords) {
		$tagdb = explode(',', $keywords);
		foreach($tagdb as $tag) {
			$aids = '';
			$tag = sax_addslashes(trim($tag));
			if ($tag) {
				$r  = $DB->fetch_one_array("SELECT tagid,aids FROM {$db_prefix}tags WHERE tag='$tag' LIMIT 1");
				if(!$r) {
					$DB->query("INSERT INTO {$db_prefix}tags (tag,usenum,aids) VALUES ('$tag', '1', '$articleid')");
					$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET tag_count=tag_count+1");
				} else {
					$aids = $r['aids'].','.$articleid;
					$DB->unbuffered_query("UPDATE {$db_prefix}tags SET usenum=usenum+1, aids='$aids' WHERE tag='$tag'");
				}
			}
		}
	}
*/	

/*	files_categories_recache();*/

	$cookiedb = array('cid', 'uid', 'filename', 'filedescription');
	dcookies($cookiedb);
    redirect('上传文件成功', 'cp.php?job=files&action=add');
}

//修改日志
if($_POST['action'] == 'modarticle') {
	$title        = trim($_POST['title']);
	$articleid    = intval($_POST['articleid']);
	$cid		  = intval($_POST['cid']);
	$description  = sax_addslashes($_POST['description']);
	$content      = sax_addslashes($_POST['content']);
	$readpassword = sax_addslashes($_POST['readpassword']);
	$alias        = trim($_POST['alias']);
	$keywords     = strtolower(sax_addslashes(trim($_POST['keywords'])));
	$closecomment   = intval($_POST['closecomment']);
	$closetrackback = intval($_POST['closetrackback']);
	$visible     = intval($_POST['visible']);
	$stick       = intval($_POST['stick']);
	// 时间变量
	$edittime    = intval($_POST['edittime']);
	$newyear     = intval($_POST['newyear']);
	$newmonth    = intval($_POST['newmonth']);
	$newday      = intval($_POST['newday']);
	$newhour     = intval($_POST['newhour']);
	$newmin      = intval($_POST['newmin']);
	$newsec      = intval($_POST['newsec']);

	$keywords    = str_replace('，', ',', $keywords);
	$keywords    = str_replace(',,', ',', $keywords);
	if (substr($keywords, -1) == ',') {
		$keywords = substr($keywords, 0, strlen($keywords)-1);
	}

	// 检查变量
	checktitle($title);
	checkcate($cid);
	checkcontent($content);
	checkkeywords($keywords);
	if ($alias) {
		checkalias($alias);
		$alias = char_cv($alias);
		$r = $DB->fetch_one_array("SELECT articleid FROM {$db_prefix}articles WHERE alias='$alias' AND articleid!='$articleid' LIMIT 1");
		if($r) {
			redirect('自定义URL名称已经存在');
		}
	}

	$title = char_cv($title);
    $article = $DB->fetch_one_array("SELECT uid,attachments,cid,visible FROM {$db_prefix}articles WHERE articleid='$articleid'");
	if ($sax_group != 1 && $sax_uid != $article['uid']) {
		redirect('您不能修改不是您写的日志', 'cp.php?job=article&action=list');
	}
	// 删除发送Trackback记录
    if ($tblogids = implode_ids($_POST['del_trackbacklog'])) {
		$DB->unbuffered_query("DELETE FROM {$db_prefix}trackbacklog WHERE trackbacklogid IN ($tblogids)");
	}

	// 修改附件
	$oldattach=array();
	$aid = $article['attachments'];
	if ($aid){
		$oldattach = unserialize(sax_stripslashes($aid));
		$nokeep = array();
		foreach ($oldattach AS $id => $value){
			if (!@in_array($id,$_POST['keep'])){
				$nokeep[$id]['filepath'] = $value['filepath'];
				$nokeep[$id]['thumb_filepath'] = $value['thumb_filepath'];
				unset($oldattach[$id]);
			}
		}
		removeattachment($nokeep);
	}
	$searcharray = array();
	$replacearray = array();
	require_once(SABLOG_ROOT.'admin/uploadfiles.php');
	if ($attachs){
		$attachs=unserialize(sax_stripslashes($attachs));
		foreach ($attachs as $key=>$value){
			$oldattach[$key]=$value;
		}
	}
	if ($oldattach){
		$oldattach = sax_addslashes(serialize($oldattach));
	} else {
		$oldattach = '';
	}
	if($attachmentids){
		$DB->unbuffered_query("UPDATE {$db_prefix}attachments SET articleid='$articleid' WHERE attachmentid IN($attachmentids)");
	}
	if ($searcharray && $replacearray) {
		$content = str_replace($searcharray, $replacearray, $content);
	}
	// 修改附件结束

	//***************** 处理tags及计数 *****************//
	$oldtags = $_POST['oldtags'] ? strtolower(sax_addslashes($_POST['oldtags'])) : '';
	updatetags($articleid, $keywords, $oldtags);
	//***************** 处理tags及计数结束 *************//

	// 修改时间
	$edittimesql = '';
	if ($edittime) {
		if (checkdate($newmonth, $newday, $newyear)) {
			if (substr(PHP_OS, 0, 3) == 'WIN' && $newyear < 1970) {
				$edittimesql = '';
			} else {
				$posttime = gmmktime($newhour, $newmin, $newsec, $newmonth, $newday, $newyear) - $timeoffset * 3600;
				$edittimesql = ", dateline='$posttime'";
			}
		}
	}

	$DB->unbuffered_query("UPDATE {$db_prefix}articles SET cid='$cid', title='$title', description='$description', content='$content', attachments='$oldattach', keywords='$keywords', closecomment='$closecomment', closetrackback='$closetrackback', visible='$visible', stick='$stick', readpassword='$readpassword', alias='$alias' $edittimesql WHERE articleid='$articleid'");
	$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET attachment_count=attachment_count+".$attachment_count);
	if ($article['cid'] != $cid) {
		$DB->unbuffered_query("UPDATE {$db_prefix}categories SET articles=articles-1 WHERE cid='".$article['cid']."'");
		if ($visible) {
			$DB->unbuffered_query("UPDATE {$db_prefix}categories SET articles=articles+1 WHERE cid='$cid'");
		}
	}
	if ($article['visible'] != $visible) {
		if ($article['visible']) {
			$visible = 0;
			$query = '-';
		} else {
			$visible = 1;
			$query = '+';
		}
		$DB->unbuffered_query("UPDATE {$db_prefix}categories SET articles=articles".$query."1 WHERE cid='".$article['cid']."'");
		$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET article_count=article_count".$query."1");
		$DB->unbuffered_query("UPDATE {$db_prefix}users SET articles=articles".$query."1 WHERE userid='$sax_uid'");
	}
	archives_recache();
	hottags_recache();
	categories_recache();
	statistics_recache();
    redirect('修改日志成功', 'cp.php?job=article&action=list');
}

//设置状态
if($action == 'visible') {
	$articleid = intval($_GET['articleid']);
	if ($articleid) {
		$article = $DB->fetch_one_array("SELECT visible,title,cid,uid FROM {$db_prefix}articles WHERE articleid='$articleid'");
		if ($sax_group != 1 && $sax_uid != $article['uid']) {
			redirect('您不能修改不是您写的日志', 'cp.php?job=article&action=list');
		}
		if ($article['visible']) {
			$visible = 0;
			$query = '-';
			$state = '隐藏';
		} else {
			$visible = 1;
			$query = '+';
			$state = '显示';
		}
		$DB->unbuffered_query("UPDATE {$db_prefix}articles SET visible='$visible' WHERE articleid='$articleid'");
		$DB->unbuffered_query("UPDATE {$db_prefix}categories SET articles=articles".$query."1 WHERE cid='".$article['cid']."'");
		$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET article_count=article_count".$query."1");
		$DB->unbuffered_query("UPDATE {$db_prefix}users SET articles=articles".$query."1 WHERE userid='".$article['uid']."'");
		archives_recache();
		categories_recache();
		statistics_recache();
		redirect('已经成功把《'.$article['title'].'》设置为"'.$state.'"状态', 'cp.php?job=article&action=list');
	} else {
		redirect('缺少参数', 'cp.php?job=article&action=list');
	}
}

//批量操作日志
if($action == 'domore') {
	if ($aids = implode_ids($_POST['article'])) {
		if($_POST['do'] == 'move') {
			$articledb = array();
			$query = $DB->query("SELECT title,articleid FROM {$db_prefix}articles WHERE articleid IN ($aids)".$uquery);
			while ($article=$DB->fetch_array($query))	{
				$articledb[] = $article;
			}
			unset($article);
			$DB->free_result($query);
			$subnav = '移动日志';
		} elseif($_POST['do'] == 'delete') {
			$articledb = array();
			$query = $DB->query("SELECT title,articleid FROM {$db_prefix}articles WHERE articleid IN ($aids)".$uquery);
			while ($article=$DB->fetch_array($query))	{
				$articledb[] = $article;
			}
			unset($article);
			$DB->free_result($query);
			$subnav = '删除日志';
		} elseif ($_POST['do'] == 'hidden') {
			$a_total = 0;
			$query  = $DB->query("SELECT cid,visible,uid FROM {$db_prefix}articles WHERE articleid IN ($aids)".$uquery);
			while($article = $DB->fetch_array($query)) {
				if ($article['visible']) {
					$a_total++;
					$DB->unbuffered_query("UPDATE {$db_prefix}users SET articles=articles-1 WHERE userid='".$article['uid']."'");
					$DB->unbuffered_query("UPDATE {$db_prefix}categories SET articles=articles-1 WHERE cid='".$article['cid']."'");
				}
			}
			$DB->unbuffered_query("UPDATE {$db_prefix}articles SET visible='0' WHERE articleid IN ($aids)");
			$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET article_count=article_count-".$a_total);
			archives_recache();
			categories_recache();
			statistics_recache();
			redirect('所选日志已隐藏', 'cp.php?job=article&action=list');
		} elseif ($_POST['do'] == 'display') {
			$a_total = 0;
			$query  = $DB->query("SELECT cid,visible,uid FROM {$db_prefix}articles WHERE articleid IN ($aids)".$uquery);
			while($article = $DB->fetch_array($query)) {
				if (!$article['visible']) {
					$a_total++;
					$DB->unbuffered_query("UPDATE {$db_prefix}users SET articles=articles+1 WHERE userid='".$article['uid']."'");
					$DB->unbuffered_query("UPDATE {$db_prefix}categories SET articles=articles+1 WHERE cid='".$article['cid']."'");
				}
			}
			$DB->unbuffered_query("UPDATE {$db_prefix}articles SET visible='1' WHERE articleid IN ($aids)");
			$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET article_count=article_count+".$a_total);
			archives_recache();
			categories_recache();
			statistics_recache();
			redirect('所选日志已显示', 'cp.php?job=article&action=list');
		} elseif ($_POST['do'] == 'stick') {
			$DB->unbuffered_query("UPDATE {$db_prefix}articles SET stick='1' WHERE articleid IN ($aids)".$uquery);
			redirect('所选日志已置顶', 'cp.php?job=article&action=list');
		} elseif ($_POST['do'] == 'unstick') {
			$DB->unbuffered_query("UPDATE {$db_prefix}articles SET stick='0' WHERE articleid IN ($aids)".$uquery);
			redirect('所选日志已取消置顶', 'cp.php?job=article&action=list');
		} else {
			redirect('没有选择具体操作');
		}
	} else {
		redirect('未选择任何日志');
	}
}
//执行移动和删除操作
if (in_array($_POST['action'], array('domove', 'dodelete'))) {
	if ($aids = implode_ids($_POST['article'])) {
		$a_total = $comment_count = $trackback_count = 0;
		if($_POST['action'] == 'domove') {
			$msg = '移动日志成功';
			$cid = intval($_POST['cid']);
			$cate = $DB->fetch_one_array("SELECT name FROM {$db_prefix}categories WHERE cid='$cid'");
			$DB->unbuffered_query("UPDATE {$db_prefix}articles SET cid='$cid' WHERE articleid IN ($aids)".$uquery);
			$catequery = $DB->query("SELECT cid, name FROM {$db_prefix}categories");
			while ($cate = $DB->fetch_array($catequery)) {
				$query = "SELECT COUNT(*) FROM {$db_prefix}articles WHERE visible = '1' AND cid='".$cate['cid']."'";
				$total = $DB->result($DB->query($query), 0);
				$DB->unbuffered_query("UPDATE {$db_prefix}categories SET articles='$total' WHERE cid='".$cate['cid']."'");
			}
		} else {
			$msg = '删除日志成功';
			$query  = $DB->query("SELECT articleid,keywords,cid,visible,uid,comments,trackbacks FROM {$db_prefix}articles WHERE articleid IN ($aids)".$uquery);
			while($article = $DB->fetch_array($query)) {
				if ($article['keywords']) {
					updatetags($article['articleid'], '', $article['keywords']);
				}
				if ($article['visible']) {
					$a_total++;
					$DB->unbuffered_query("UPDATE {$db_prefix}users SET articles=articles-1 WHERE userid='".$article['uid']."'");
					$DB->unbuffered_query("UPDATE {$db_prefix}categories SET articles=articles-1 WHERE cid='".$article['cid']."'");
				}
				$comment_count = $comment_count + $article['comments'];
				$trackback_count = $trackback_count + $article['trackbacks'];
			}
			$query  = $DB->query("SELECT attachmentid,filepath,thumb_filepath FROM {$db_prefix}attachments WHERE articleid IN ($aids)");
			if ($DB->num_rows($query)) {
				$nokeep = array();
				while($attach = $DB->fetch_array($query)) {
					$nokeep[$attach['attachmentid']] = $attach;
				}
				removeattachment($nokeep);
			}
			$DB->unbuffered_query("DELETE FROM {$db_prefix}articles WHERE articleid IN ($aids)".$uquery);
			$DB->unbuffered_query("DELETE FROM {$db_prefix}comments WHERE articleid IN ($aids)");
			$DB->unbuffered_query("DELETE FROM {$db_prefix}trackbacks WHERE articleid IN ($aids)");
			$DB->unbuffered_query("DELETE FROM {$db_prefix}trackbacklog WHERE articleid IN ($aids)");
			$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET article_count=article_count-".$a_total);
			$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET comment_count=comment_count-".$comment_count);
			$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET trackback_count=trackback_count-".$trackback_count);
			hottags_recache();
			archives_recache();
			statistics_recache();
		}
		categories_recache();
		redirect($msg, 'cp.php?job=article&action=list');
	} else {
		redirect('未选择任何日志');
	}
}

//操作结束

if (in_array($action, array('add', 'mod'))) {
//自动显示tag
//amxku.net 2008-09-16
    $showtaglist.="<input type='hidden' name='tags' value=''>";
    $query=$DB->query("SELECT tag FROM {$db_prefix}tags ORDER BY usenum DESC");
    $showtagdb=array();
    while ($showtag = $DB->fetch_array($query)) {
    array_push($showtagdb,$showtag['tag']);
    }
    unset($showtag);
    $DB->free_result($query);
    $all_show_tags = "'".join("','",$showtagdb)."'";
    //pr($showtagdb);
    $tag_js="\n<script type='text/javascript'>\nvar custom_array = new Array();\ncustom_array=[".$all_show_tags."];\n</script>\n<script type='text/javascript' src='$options[url]include/jscript/autosuggestion.js'></script>\n";
    $showtaglist='';
//自动显示tag
	$article = array();
	$smdir = SABLOG_ROOT.'images/smiles/';
	$insertsm = false;
	if(is_dir($smdir)) {
		$dirs = dir($smdir);
		$smfiles = array();
		while ($file = $dirs->read()) {
			$filepath = $smdir.$file;
			$pathinfo = pathinfo($filepath);
			if(is_file($filepath) && in_array($pathinfo['extension'],array('gif','jpg','jpeg','png'))) {
				$smfiles[] = $file;
			}
		}
		unset($file);
		$dirs->close();
		$insertsm = true;
		//获取表情目录的URL
		$dirurl = $options['url'];
	}

	if ($action == 'mod') {
		$act = 'modarticle';
		$tdtitle = '修改日志';
		$articleid = intval($_GET['articleid']);
		$article = $DB->fetch_one_array("SELECT a.*,u.username FROM {$db_prefix}articles a
			LEFT JOIN {$db_prefix}users u ON u.userid=a.uid
			WHERE articleid='$articleid'");
		if (empty($article)) {
			redirect('日志不存在');
		}
		if ($sax_group != 1 && $sax_uid != $article['uid']) {
			redirect('您不能修改不是您写的日志', 'cp.php?job=article&action=list');
		}
		$article['keywords'] = htmlspecialchars($article['keywords']);
		$article['description'] = str_replace('\r\n', '', $article['description']);
		$article['content'] = str_replace('\r\n', '', $article['content']);

		//发送的Trackback记录
		$query = $DB->query("SELECT * FROM {$db_prefix}trackbacklog WHERE articleid = '".$article['articleid']."'");
		$tblogdb = array();
		while($tblog = $DB->fetch_array($query)) {
			$tblog['pingurl'] = htmlspecialchars($tblog['pingurl']);
			$tblogdb[] = $tblog;
		}
		unset($tblog);

		//附件
		$query = $DB->query("SELECT attachmentid,articleid,dateline,filename,filesize FROM {$db_prefix}attachments WHERE articleid = '".$article['articleid']."'");
		$attachdb = array();
		while($attach = $DB->fetch_array($query)) {
			$attach['filename'] = htmlspecialchars($attach['filename']);
			$attach['dateline'] = sadate('Y-m-d H:i:s',$attach['dateline']);
			$attach['filesize'] = sizecount($attach['filesize']);
			$attachdb[] = $attach;
		}
		unset($attach);

		$closecomment_check = $article['closecomment'] ? 'checked' : '';
		$closetrackback_check = $article['closetrackback'] ? 'checked' : '';
		$visible_check = $article['visible'] ? 'checked' : '';
		$stick_check = $article['stick'] ? 'checked' : '';
	} else {
		$act = 'addfiles';
		$tdtitle = '上传新文档';
		$file['filedescription'] = '';
		$article['cid'] = intval($_GET['cid']);
	}
	$subnav = $tdtitle;
	@list($newyear, $newmonth, $newday, $newhour, $newmin, $newsec) = explode('-', sadate('Y-n-j-H-i-s', $timestamp));
}//end add or mod

if ($action == 'list') {
	$cid = intval($_GET['cid'] ? $_GET['cid'] : $_POST['cid']);
	$uid = intval($_GET['uid'] ? $_GET['uid'] : $_POST['uid']);
	$view = $_GET['view'] ? $_GET['view'] : $_POST['view'];
	$m = $_GET['m'] ? $_GET['m'] : $_POST['m'];

	$addquery = $pagelink = '';
	$subnav = '全部的日志';
	if ($sax_group != 1) {
		$subnav = '您发表的全部日志';
	}
	if ($_GET['tag']) {
		$item = sax_addslashes($_GET['tag']);
		$tag = $DB->fetch_one_array("SELECT usenum,aids FROM {$db_prefix}tags WHERE tag='$item' LIMIT 1");
		if (!$tag) {
			redirect('标签不存在', 'cp.php?job=article&action=list');
		}
		$addquery .= " AND a.articleid IN (".$tag['aids'].")";
		$subnav = 'Tags:'.$item;
		$pagelink .= '&tag='.urlencode($item);
	}
	if ($view == 'stick') {
		$addquery .= " AND a.stick='1'";
		$subnav = '置顶的日志';
		$pagelink .= '&view=stick';
	} elseif ($view == 'hidden') {
		$addquery .= " AND a.visible='0'";
		$subnav = '隐藏的日志';
		$pagelink .= '&view=hidden';
	} elseif ($view == 'display') {
		$addquery .= " AND a.visible='1'";
		$subnav = '显示的日志';
		$pagelink .= '&view=display';
	}
	if ($cid) {
		$cate = $DB->fetch_one_array("SELECT name FROM {$db_prefix}categories WHERE cid='$cid'");
		$subnav = '分类:'.$cate['name'];
		$addquery .= " AND a.cid='$cid'";
		$pagelink .= '&cid='.$cid;
	}
	if ($uid) {
		$user = $DB->fetch_one_array("SELECT username FROM {$db_prefix}users WHERE userid='$uid'");
		$subnav = '用户:'.$user['username'];
		$addquery .= " AND a.uid='$uid'";
		$pagelink .= '&uid='.$uid;
	}
	if ($m) {
		$mdb = explode('-', $m);
		list($start, $end) = explode('-', gettimestamp($mdb[0],$mdb[1]));
		$pagelink .= '&m='.$m;
		$subnav = '在'.$mdb[0].'年'.$mdb[1].'月里';
		//*******************************//
		$addquery .= " AND a.dateline >= '".correcttime($start)."' AND a.dateline < '".correcttime($end)."' ";
	}
	// 搜索部分
	$keywords = sax_addslashes(trim($_POST['keywords'] ? $_POST['keywords'] : $_GET['keywords']));
	if ($keywords) {
		$keywords = str_replace("_","\_",$keywords);
		$keywords = str_replace("%","\%",$keywords);
		if(preg_match("(AND|\+|&|\s)", $keywords) && !preg_match("(OR|\|)", $keywords)) {
			$andor = ' AND ';
			$sqltxtsrch = '1';
			$keywords = preg_replace("/( AND |&| )/is", "+", $keywords);
		} else {
			$andor = ' OR ';
			$sqltxtsrch = '0';
			$keywords = preg_replace("/( OR |\|)/is", "+", $keywords);
		}
		$keywords = str_replace('*', '%', addcslashes($keywords, '%_'));
		foreach(explode("+", $keywords) AS $text) {
			$text = trim($text);
			if($text) {
				$sqltxtsrch .= $andor;
				$sqltxtsrch .= "(a.content LIKE '%".$text."%' OR a.description LIKE '%".$text."%' OR a.title LIKE '%".$text."%')";
			}
		}
		$addquery .= " AND ($sqltxtsrch)";
		$subnav = '搜索结果';
		$pagelink .= '&keywords='.urlencode($keywords);
	}

	$pagenum = 20;
	if($page) {
		$start_limit = ($page - 1) * $pagenum;
	} else {
		$start_limit = 0;
		$page = 1;
	}
	$rs = $DB->fetch_one_array("SELECT count(*) AS articles FROM {$db_prefix}articles a WHERE 1 $addquery $uquery");
	$total = $rs['articles'];
	$multipage = multi($total, $pagenum, $page, 'cp.php?job=article&action=list'.$pagelink);

	$query = $DB->query("SELECT a.articleid,a.title,a.cid,a.uid,a.dateline,a.comments,a.trackbacks,a.attachments,a.visible,a.stick,c.name as cname,u.username
		FROM {$db_prefix}articles a
		LEFT JOIN {$db_prefix}categories c ON c.cid=a.cid
		LEFT JOIN {$db_prefix}users u ON u.userid=a.uid
		WHERE 1 $addquery $uquery ORDER BY dateline DESC LIMIT $start_limit, $pagenum");

	$articledb = array();
    while ($article = $DB->fetch_array($query)) {
		$article['dateline'] = sadate('Y-m-d H:i',$article['dateline']);
		$articledb[] = $article;
	}
	unset($article);
	$DB->free_result($query);
} //end list

$navlink_L = ' &raquo; <a href="cp.php?job=article">日志管理</a>'.($subnav ? ' &raquo; '.$subnav : '');
cpheader($subnav);
include template('files');
?>